package com.ruoyi.common.utils.http;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpClientUtil {

    /**
     * 创建HttpClient
     */
    private static final CloseableHttpClient CLIENT = HttpClients.createDefault();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * GET
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGet(String url) throws IOException {
        return doGet(url, null);
    }

    /**
     * GET（重载方法，带headers参数）
     *
     * @param url
     * @param headers
     * @return
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> headers) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        setHeaders(httpGet, headers); // 设置headers
        CloseableHttpResponse response = CLIENT.execute(httpGet); // 执行请求
        return handleResponse(response); // 处理响应
    }

    /**
     * POST
     *
     * @param url
     * @param jsonBody
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String jsonBody) throws IOException {
        return doPost(url, jsonBody, null);
    }

    /**
     * POST（重载方法，带headers参数）
     *
     * @param url
     * @param jsonBody
     * @param headers
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String jsonBody, Map<String, String> headers) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        setHeaders(httpPost, headers); // 设置headers
        httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8)); // 设置请求体
        CloseableHttpResponse response = CLIENT.execute(httpPost); // 执行请求
        return handleResponse(response); // 处理响应
    }

    /**
     * PUT
     *
     * @param url
     * @param jsonBody
     * @return
     * @throws IOException
     */
    public static String doPut(String url, String jsonBody) throws IOException {
        return doPut(url, jsonBody, null);
    }

    /**
     * PUT（重载方法，带headers参数）
     *
     * @param url
     * @param jsonBody
     * @param headers
     * @return
     * @throws IOException
     */
    public static String doPut(String url, String jsonBody, Map<String, String> headers) throws IOException {
        HttpPut httpPut = new HttpPut(url);
        setHeaders(httpPut, headers); // 设置headers
        httpPut.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8)); // 设置请求体
        CloseableHttpResponse response = CLIENT.execute(httpPut); // 执行请求
        return handleResponse(response); // 处理响应
    }

    /**
     * DELETE
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doDelete(String url) throws IOException {
        return doDelete(url, null);
    }

    /**
     * DELETE（重载方法，带headers参数）
     *
     * @param url
     * @param headers
     * @return
     * @throws IOException
     */
    public static String doDelete(String url, Map<String, String> headers) throws IOException {
        HttpDelete httpDelete = new HttpDelete(url);
        setHeaders(httpDelete, headers); // 设置headers
        CloseableHttpResponse response = CLIENT.execute(httpDelete); // 执行请求
        return handleResponse(response); // 处理响应
    }

    /**
     * 设置headers的方法
     *
     * @param httpRequest
     * @param headers
     */
    private static void setHeaders(Object httpRequest, Map<String, String> headers) {
        if (headers != null) {
            headers.forEach((key, value) -> {
                if (httpRequest instanceof HttpGet) {
                    ((HttpGet) httpRequest).addHeader(key, value);
                } else if (httpRequest instanceof HttpPost) {
                    ((HttpPost) httpRequest).addHeader(key, value);
                } else if (httpRequest instanceof HttpPut) {
                    ((HttpPut) httpRequest).addHeader(key, value);
                } else if (httpRequest instanceof HttpDelete) {
                    ((HttpDelete) httpRequest).addHeader(key, value);
                }
            });
        }
    }

    /**
     * 处理响应的方法，将响应转换成字符串返回
     *
     * @param response HttpResponse对象
     * @return 响应内容字符串
     * @throws IOException
     */
    private static String handleResponse(CloseableHttpResponse response) throws IOException {
        // 获取响应实体

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            // 如果响应实体为空，则返回空字符串
            return "";
        }
        // 将响应实体转换成字符串
        String responseBody = "";
        try {
             responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 关闭响应实体的输入流
        EntityUtils.consume(entity);
        // 返回响应内容字符串
        return responseBody;
    }





}
